<template>
  <el-dialog
    v-model="dialogVisible"
    :title="dialogTitle"
    width="500px"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
    >
      <el-form-item label="客户名称">
        <el-input v-model="customer.customerName" disabled />
      </el-form-item>
      
      <el-form-item label="审批操作">
        <el-tag :type="action === 'approve' ? 'success' : 'danger'" size="large">
          {{ action === 'approve' ? '通过' : '拒绝' }}
        </el-tag>
      </el-form-item>
      
      <el-form-item 
        label="审批意见" 
        prop="comment"
        :rules="commentRules"
      >
        <el-input
          v-model="form.comment"
          type="textarea"
          :rows="4"
          :placeholder="commentPlaceholder"
          maxlength="500"
          show-word-limit
        />
      </el-form-item>
      
      <el-form-item 
        v-if="action === 'reject'"
        label="拒绝原因" 
        prop="rejectReason"
        :rules="rejectReasonRules"
      >
        <el-input
          v-model="form.rejectReason"
          type="textarea"
          :rows="3"
          placeholder="请详细说明拒绝原因"
          maxlength="200"
          show-word-limit
        />
      </el-form-item>
    </el-form>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button 
          type="primary" 
          @click="handleSubmit"
          :loading="loading"
        >
          {{ action === 'approve' ? '确认通过' : '确认拒绝' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import { ref, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { approveCustomer } from '../../api/customer.js'

export default {
  name: 'CustomerApprovalDialog',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    customer: {
      type: Object,
      default: null
    },
    action: {
      type: String,
      default: 'approve', // 'approve' 或 'reject'
      validator: (value) => ['approve', 'reject'].includes(value)
    }
  },
  emits: ['update:visible', 'success'],
  setup(props, { emit }) {
    const dialogVisible = computed(() => props.visible)
    const loading = ref(false)
    const formRef = ref(null)
    
    const form = ref({
      comment: '',
      rejectReason: ''
    })
    
    // 对话框标题
    const dialogTitle = computed(() => {
      return props.action === 'approve' ? '审批通过' : '审批拒绝'
    })
    
    // 审批意见占位符
    const commentPlaceholder = computed(() => {
      return props.action === 'approve' 
        ? '请输入审批通过的意见（可选）' 
        : '请输入审批拒绝的意见'
    })
    
    // 审批意见验证规则
    const commentRules = computed(() => {
      if (props.action === 'reject') {
        return [
          { required: true, message: '请输入审批意见', trigger: 'blur' },
          { min: 5, message: '审批意见至少5个字符', trigger: 'blur' }
        ]
      }
      return []
    })
    
    // 拒绝原因验证规则
    const rejectReasonRules = computed(() => {
      if (props.action === 'reject') {
        return [
          { required: true, message: '请输入拒绝原因', trigger: 'blur' },
          { min: 10, message: '拒绝原因至少10个字符', trigger: 'blur' }
        ]
      }
      return []
    })
    
    // 监听对话框显示状态
    watch(() => props.visible, (visible) => {
      if (visible) {
        resetForm()
      }
    })
    
    // 重置表单
    const resetForm = () => {
      form.value = {
        comment: '',
        rejectReason: ''
      }
      if (formRef.value) {
        formRef.value.clearValidate()
      }
    }
    
    // 提交审批
    const handleSubmit = async () => {
      if (!formRef.value) return
      
      try {
        // 验证表单
        await formRef.value.validate()
        
        // 确认对话框
        const confirmMessage = props.action === 'approve' 
          ? '确认通过该客户申请吗？' 
          : '确认拒绝该客户申请吗？'
        
        await ElMessageBox.confirm(confirmMessage, '确认审批', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: props.action === 'approve' ? 'success' : 'warning'
        })
        
        loading.value = true
        
        // 构建审批数据
        const approvalData = {
          customerId: props.customer.id,
          approvalResult: props.action === 'approve' ? 'APPROVED' : 'REJECTED',
          approvalComment: form.value.comment,
          rejectReason: props.action === 'reject' ? form.value.rejectReason : null
        }
        
        // 调用审批API
        await approveCustomer(approvalData)
        
        ElMessage.success(
          props.action === 'approve' ? '审批通过成功' : '审批拒绝成功'
        )
        
        emit('success')
        handleClose()
        
      } catch (error) {
        if (error !== 'cancel') {
          console.error('审批操作失败:', error)
          ElMessage.error('审批操作失败')
        }
      } finally {
        loading.value = false
      }
    }
    
    // 关闭对话框
    const handleClose = () => {
      emit('update:visible', false)
    }
    
    return {
      dialogVisible,
      loading,
      formRef,
      form,
      dialogTitle,
      commentPlaceholder,
      commentRules,
      rejectReasonRules,
      handleSubmit,
      handleClose
    }
  }
}
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}

.dialog-footer .el-button {
  margin-left: 10px;
}

:deep(.el-form-item__label) {
  font-weight: 600;
}

:deep(.el-textarea__inner) {
  resize: vertical;
}
</style>
